//
//  DailyImgShowView.swift
//  MM2
//
//  Created by 李成明 on 2022/1/2.
//

import UIKit
import Kingfisher
import JXPhotoBrowser

class DailyImgShowView: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setupUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private var viewArray: [UIImageView] = []
    private var imgArray: [String] = []
    var realImgArray: [UIImage] = [] {
        didSet {
            updateUIInRealArray()
        }
    }
    
    
    private(set) var viewHeight: CGFloat = 0
    var isAddingImg = false
    private var addImgClosure: ((DailyImgShowView) -> Void)?
    
    func setImage(imgArr: [String]) {
        imgArray = imgArr
        updateUI()
    }
    
    private func updateUIInRealArray() {
        viewArray.forEach { $0.frame = CGRect.zero }
        setViewFrame(useReal: true)
        for (index, model) in realImgArray.enumerated() {
            viewArray[safe: index]?.image = model
        }
    }
    
    private func updateUI() {
        viewArray.forEach { $0.frame = CGRect.zero }
        setViewFrame(useReal: false)
        for (index, model) in imgArray.enumerated() {
            guard let url = URL.init(string: model) else { continue }
            viewArray[safe: index]?.kf.setImage(with: url, placeholder: placeHolderImg)
        }
    }
    
    private func setViewFrame(useReal: Bool) {
        viewArray.forEach {
            $0.frame = CGRect.zero
            $0.image = nil
        }
        let num =  useReal ? (realImgArray.count > 6 ? 6 : realImgArray.count) : (imgArray.count > 6 ? 6 : imgArray.count)
        let size = DailyCountTool.countImageSize(imgNum: num)
        
        let width = size.width
        let height = size.height
        let space = 4.0
        
        if num == 0 {
            viewHeight = 0
        } else if num > 0 && num <= 3 { viewHeight = size.height }
        else if(num >= 4 && num <= 6) { viewHeight = size.height*2 + space }
        
        for (index, item) in viewArray.enumerated() {
            if index >= num { break }
            switch index {
            case 0:
                item.frame = CGRect(x: 0, y: 0, width: width, height: height)
            case 1:
                item.frame = CGRect(x: width + space, y: 0, width: width, height: height)
            case 2:
                if num != 4 {
                    item.frame = CGRect(x: (width + space)*2, y: 0, width: width, height: height)
                } else {
                    item.frame = CGRect(x: 0, y: height + space, width: width, height: height)
                }
            case 3:
                if num != 4 {
                    item.frame = CGRect(x: 0, y: height + space, width: width, height: height)
                } else {
                    item.frame = CGRect(x: width + space, y: height + space, width: width, height: height)
                }
            case 4:
                item.frame = CGRect(x: width + space, y: height + space, width: width, height: height)
            case 5:
                item.frame = CGRect(x: (width + space)*2, y: height + space, width: width, height: height)
            default:
                item.frame = CGRect.zero
            }
        }
    }
    
    private func setupUI() {
        for _ in 0...5 {
            let view = UIImageView()
            view.layer.masksToBounds = true
            view.layer.cornerRadius = 4
            view.contentMode = .scaleAspectFill
            
            view.isUserInteractionEnabled = true
            let tap = UITapGestureRecognizer(target: self, action: #selector(imgClick(sender:)))
            view.addGestureRecognizer(tap)
            
            viewArray.append(view)
            addSubview(view)
        }
    }
    
    @objc private func imgClick(sender: UITapGestureRecognizer) {
        if isAddingImg {
            addImgClosure?(self)
            return
        }
        let browser = JXPhotoBrowser()
        browser.numberOfItems = {
            return self.imgArray.count
        }
        browser.reloadCellAtIndex = { context in
            let browserCell = context.cell as? JXPhotoBrowserImageCell
            let index = context.index
            let imgUrlStr = self.imgArray[index]
            browserCell?.imageView.setImageWithUrlStr(imgUrlStr)
        }
        
        browser.transitionAnimator = JXPhotoBrowserSmoothZoomAnimator(transitionViewAndFrame: { (index, destinationView) -> JXPhotoBrowserSmoothZoomAnimator.TransitionViewAndFrame? in
            let transitionView = UIImageView()
            transitionView.setImageWithUrlStr(self.imgArray[index])
            transitionView.contentMode = .scaleAspectFit
            transitionView.clipsToBounds = true
            
            let animationView = self.viewArray[index]
            let thumbnailFrame = animationView.convert(animationView.bounds, to: destinationView)
            return (transitionView, thumbnailFrame)
        })
        
        let currentIndex = viewArray.firstIndex(of: sender.view as! UIImageView)
        browser.pageIndex = currentIndex ?? 0
        browser.show()
    }
    
    @discardableResult
    func addImgClick(_ closure:((DailyImgShowView) -> Void)?) -> DailyImgShowView {
        addImgClosure = closure
        return self
    }
}
